﻿/*

detail pls visit : www.json.org
usage :
import  com.adobe.serialization.json.*;

	private var MyCJ:cacheJSON = new cacheJSON();
	
	// there is two way to send variables to server.
	MyCJ.data = { str:"hihi", foo:true, num: 12354 };
	MyCJ.sent("yourServerAction.php");

	// you can also write like this
	var _abc:Object = new Object();
	_abc.str="hihi";
	_abc.foo=true;
	_abc.num=12354;
	MyCJ.sent("yourServerAction.php", _abc);
	
	// if you want to receive the server return value by JSON
	MyCJ.addEventListener(LoadEvent.ONLOAD, handleYourReturnValue);
	MyCJ.sent("GiveMeJSON.php");
	function handleYourReturnValue(e:LoadEvent):void{
		trace("action:"+ e.data.url);
		trace("value info:"+ e.data.info);
	}
*/


package com.cf.core.Utils{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoaderDataFormat;
	import com.adobe.serialization.json.*;
	import com.cf.core.events.LoadEvent;
	public class cacheJSON extends EventDispatcher{
		private var G_URL:String;
		private var G_Loader:URLLoader;
		private var G_value:Object;
		public function set data(_o:Object):void{G_value=_o}
		public function get data():Object{return G_value}
		
		public function cacheJSON():void{
			RELEASE();
		}//fn
		public function RELEASE():void{
			G_Loader=new URLLoader();
			G_value=new Object();
			G_URL="";
		}//fn
		
		public function sent(_url:String="",_value:Object=null):void{
			G_URL = _url;
			var _action:URLRequest = new URLRequest(G_URL);
			var _tmpVar:String;	// to carry STRING by JSON format.
			if( _value!=null){
				// copy or append the variables
				for(var i in _value){
					this.data[i] = _value[i];
				}//for
			}//if
			if( this.data!=null ){
				_tmpVar = JSON.encode( this.data );
				_action.method = URLRequestMethod.POST;
				_action.contentType = URLLoaderDataFormat.TEXT;
				_action.data = _tmpVar;
				debug.msg('cacheJSON : Value will sent to server :-'+ _tmpVar );
			}//if
			
			G_Loader.addEventListener(Event.COMPLETE, handleOnload);
			G_Loader.load(_action);
			this.data=new Object();
		}//fn
		private function handleOnload(e:Event):void{
			G_Loader.removeEventListener(Event.COMPLETE, handleOnload);
			var _obj:Object = JSON.decode(G_Loader.data);
			try{
				// debug.msg("cacheJSON : success return from :: "+ G_URL);
				dispatchEvent(new LoadEvent(LoadEvent.ONLOAD, { url: G_URL, info: _obj }) );
			}catch(ee){ debug.msg("cacheJSON : Fail to get value from :: "+ G_URL); }
		}//fn
	}//class
}//package